package com.solidit.cassandra.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.solidit.cassandra.controller.persistance.model.Events;
import com.solidit.cassandra.controller.persistance.util.CassandraConectionManager;

@Service
public class SaveEventService {
	private static final Logger logger = LoggerFactory
			.getLogger(SaveEventService.class);

	@Autowired
	private CassandraConectionManager conn;

	private List <String> columnas = new ArrayList<String>();
	private List <String> valores = new ArrayList<String>();
	private String query;
	
	

	@SuppressWarnings("unchecked")
	public void jsonEvent(Events ev) {
		try {
			ObjectMapper mapperJson = new ObjectMapper();
			Map<String, Object> js;
			// {"tipo":true,"dicc":{}}
			js = mapperJson.readValue(ev.getJson(), Map.class);
			for (Map.Entry<String, Object> e : js.entrySet()) {
				if (CharSequence.class.isInstance(e.getValue())) {
					columnas.add(e.getKey());
					valores.add("'"+ e.getValue().toString()+"'");
					// String
				} else {
					columnas.add(e.getKey());
					valores.add(e.getValue().toString());
				}
			}
			String col = StringUtils.join(columnas,(","));
			String val = StringUtils.join(valores,(","));		
			query = "INSERT INTO geomanagement." +ev.getNombre()+ "(" + col + ") VALUES (" + val + ")";
			conn.getSession().execute(query);
		} catch (Exception e) {
			logger.warn("ERROR AL INGRESAR LOS DATOS", e);
		}

	}

}
